/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dale2507.gates.gate.logic;

import dale2507.gates.GatePlugin;
import dale2507.gates.Messenger;
import dale2507.gates.data.Settings;
import dale2507.gates.exceptions.GateConnectionException;
import dale2507.gates.exceptions.PermissionException;
import dale2507.gates.gate.Activator;
import dale2507.gates.gate.Gate;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitScheduler;

/**
 *
 * @author Dale
 */
public class FailAfterDial extends IActivatorLogic {
    
    private BukkitScheduler scheduler = Bukkit.getScheduler();
    private int dialler;
    
    public FailAfterDial(Activator activator, CommandSender cs) {
        super(activator, cs);
    }

    @Override
    public void run() {
        this.getActivator().setSourceStatus(Gate.Status.DIALLING);
        dialler = this.scheduler.scheduleAsyncRepeatingTask(GatePlugin.getInstance(), 
                new Dialler(), 
                Settings.getInstance().connection.chevronDelay(), 
                Settings.getInstance().connection.chevronDelay());
    }

    @Override
    public void stop() {
        scheduler.cancelTask(dialler);
    }
    
    private class Dialler implements Runnable {
        
        private boolean lastDial = false;
        private int ticker = 0;

        @Override
        public void run() {
            try {
                if (!lastDial) {
                    lastDial = getActivator().dialChevron(ticker);
                    ticker++;
                } else {
                    getActivator().findDestination();
                    getActivator().checkDestination();
                    getActivator().establish();
                    scheduler.cancelTask(dialler);
                }
            } catch (GateConnectionException | PermissionException ex) {
                sendMessage(Messenger.ERROR, ex.getMessage());
                getActivator().setSourceStatus(Gate.Status.INACTIVE);
                scheduler.cancelTask(dialler);
            }
        }
        
    }
}
